20180114

Class(類別) 用來設計需要的Object(物件),為物件的模板,

其中包含instance(實例),可存取的object(如list),也可定義method(由第一個參數為self的方法)。

舉例來說,

student這個類別為class,裏頭的學生則為instance,

好學生名單(list)可以是object,而方法可以給定每一個學生(instance) 名稱、分數等等。

為了使模板起到作用,我們通常會在class裏頭定義一些共用的東西,

利用定義__init__來達成,如下:

Class Student(object):
  def __init__(self,name,score):
    self.name = name
    self.score = score

[練習]

class Student(object):
  good_student={}
  def __init__(self,name,score):
    self.name=name
    self.score=score
  def filter(self,name,score):
    if score >= 60:
      self.good_student[name]=score
      print (name + " added to good student")

exam = Student("Ramone",99)
exam.filter("Ramone",99)

results matching ""

    No results matching ""